package com.jrx.anytxn.accounting.service.impl;

import com.jrx.anytxn.accounting.bean.BillingBean;
import com.jrx.anytxn.accounting.bean.ConsolidationCheckBean;
import com.jrx.anytxn.accounting.bean.DealBillBean;
import com.jrx.anytxn.accounting.entity.GaSubjectDetailTransition;
import com.jrx.anytxn.accounting.entity.GaVoucherExcpReport;
import com.jrx.anytxn.accounting.entity.GaVoucherInfo;
import com.jrx.anytxn.accounting.mapper.ext.ExtVoucherInfoMapper;
import com.jrx.anytxn.accounting.service.IConsolidationService;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.common.uitl.CollectorsUtils;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.GaSubjectTable;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.account.ISubjectTableService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 批次的service实现类
 *
 * @author Sunset
 * @version 1.0
 * @date 2019/10/22
 */
@Service
public class ConsolidationServiceImpl implements IConsolidationService {

    @Resource
    private ExtVoucherInfoMapper extVoucherInfoMapper;
    @Autowired
    private ISubjectTableService subjectTableService;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private ISegmentService iSegmentService;

    @Override
    public BillingBean getBillingBean(Map<String, DealBillBean> subjectDetailMap, String batchTaskId) throws SegmentException {
        BillingBean billingBean = new BillingBean();
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
        Date today = org.getToday();

        //获取有效的科目号
        List<GaSubjectTable> allSubject = subjectTableService.getAllSubjectId(Constant.STATUS_1);
        if (CollectionUtils.isEmpty(allSubject)) {
            return billingBean;
        }
        //科目号集合不为空时
        for (GaSubjectTable subject : allSubject) {
            //获取科目业务日期下金额 的变化对象
            DealBillBean dealBillBean = subjectDetailMap.get(subject.getSubjectId());
            //空  当天没有该科目的交易
            if (dealBillBean == null) {
                dealBillBean = new DealBillBean();
                subjectDetailMap.put(subject.getSubjectId(),dealBillBean);
            }

            //获取上级科目号字段，汇总上级科目
            if (StringUtils.isNoneBlank(subject.getParentSubject()) && !subject.getParentSubject().equals(subject.getSubjectId())) {
                DealBillBean dealBillBeanParent = subjectDetailMap.get(subject.getParentSubject());
                if (dealBillBeanParent == null) {
                    subjectDetailMap.put(subject.getParentSubject(),dealBillBean);
                }else{
                    subjectDetailMap.get(subject.getParentSubject()).add(dealBillBean);
                }
            }
        }

        for(Map.Entry<String, DealBillBean> entry : subjectDetailMap.entrySet()){
            String subjectId = entry.getKey();
            DealBillBean dealBillBean = entry.getValue();
            GaSubjectTable subject=allSubject.stream().filter(s->s.getSubjectId().equals(subjectId)).findAny().get();

            BigDecimal debitAmt = dealBillBean.getDebitAmount();
            BigDecimal creditAmt = dealBillBean.getCreditAmount();
            int debitCount = dealBillBean.getDebitCount();
            int creditCount = dealBillBean.getCreditCount();

            //处理明细
            GaSubjectDetailTransition newSubjectDetailTransition = this.buildSubjectDetailTransition(subject);
            //将业务日期，科目号，机构号放到 科目明细对象中
            newSubjectDetailTransition.setDetailDate(today);
            newSubjectDetailTransition.setCreditAmount(creditAmt);
            newSubjectDetailTransition.setDebitAmount(debitAmt);
            newSubjectDetailTransition.setCreditCount(creditCount);
            newSubjectDetailTransition.setDebitCount(debitCount);
            //批次任务id（与分库绑定）
            newSubjectDetailTransition.setBatchTaskId(batchTaskId);
            //当前业务不存在 放到添加集合中
            newSubjectDetailTransition.setRecordVersionNumber(Constant.VERSION_NUMBER);
            //主键
            newSubjectDetailTransition.setId(iSegmentService.getId("GaSubjectDetailTransition"));
            //放入添加科目明细集合中
            billingBean.addSubjectDetailTransition(newSubjectDetailTransition);
        }
        return billingBean;
    }

    /**
     * 创建科目明细表
     *
     * @return
     */
    private GaSubjectDetailTransition buildSubjectDetailTransition(GaSubjectTable subject) {
        GaSubjectDetailTransition subjectDetailTransition = new GaSubjectDetailTransition();
        subjectDetailTransition.setDebitAmount(BigDecimal.ZERO);
        subjectDetailTransition.setDebitCount(0);
        subjectDetailTransition.setCreditAmount(BigDecimal.ZERO);
        subjectDetailTransition.setCreditCount(0);
        subjectDetailTransition.setUpdateBy("subjectDetail");
        subjectDetailTransition.setTenantId(subject.getTenantId());
        subjectDetailTransition.setOrganizationId(subject.getOrganizationId());
        subjectDetailTransition.setSubjectId(subject.getSubjectId());
        return subjectDetailTransition;
    }

    /**
     * 并账检查测试
     *
     * @param gaVoucherInfo 传票流水表记录
     * @return ConsolidationCheckBean 并账检查测试
     */
    @Override
    public ConsolidationCheckBean getConsolidationCheckBean(GaVoucherInfo gaVoucherInfo) {
        ConsolidationCheckBean bean = new ConsolidationCheckBean();
        List<GaVoucherExcpReport> list = new ArrayList<>();
        //根据流水号查询传票流水表
        List<GaVoucherInfo> gaVoucherInfoList = extVoucherInfoMapper.selectVoucherListByFlownoForBatch(gaVoucherInfo.getFlowno());
        //根据 贷方金额，借方金额分组合并金额
        Map<String, BigDecimal> limitMap = gaVoucherInfoList.stream().collect(Collectors.groupingBy(GaVoucherInfo::getSign, CollectorsUtils.summingBigDecimal(GaVoucherInfo::getAmount)));
        BigDecimal c = limitMap.get("C");
        BigDecimal d = limitMap.get("D");
        if (c == null || d == null || c.compareTo(d) != 0) {
            list.addAll(BeanMapping.copyList(gaVoucherInfoList, GaVoucherExcpReport.class));
        }
        bean.setInterestVoucherExcpReportList(list);
        return bean;
    }
}